package cn.z2huo.knowledge.concurrency.callable.callable;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * <p>
 *
 * @author z2huo
 */
class ExecutorServiceSubmitTest {

    public static void submitMethodTest() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Deque<Future<String>> resultList = new LinkedList<>();
        for (int i = 0; i < 10; i++) {
            resultList.add(executorService.submit(new MyCallable(i)));
        }
        System.out.println("wait result, this is other operate");
        for (Future<String> result : resultList) {
            try {
                System.out.println(result.get());
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.close();
    }

    public static void invokeAllMethodTest() {
        ExecutorService executorService = Executors.newCachedThreadPool();

        List<MyCallable> callables = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            callables.add(new MyCallable(i));
        }

        List<Future<String>> results;
        try {
            results = executorService.invokeAll(callables);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        for (Future<String> result : results) {
            try {
                System.out.println(result.get());
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.close();
    }

    public static void main(String[] args) {

        submitMethodTest();

//        invokeAllMethodTest();
    }

}
